package com.eduction.controller;

import com.eduction.bean.SessionUser;
import com.eduction.common.ReturnCode;
import com.eduction.common.utils.DocToPDFConverter;
import com.eduction.common.utils.DocxToPDFConverter;
import com.eduction.modules.system.entity.ArgumentationMaterial;
import com.eduction.modules.system.entity.QuestionnaireSurvey;
import com.eduction.modules.system.entity.School;
import com.eduction.modules.system.entity.SchoolItemData;
import com.eduction.modules.target.entity.Detailed;
import com.eduction.modules.target.entity.IndexTargetEntity;
import com.eduction.modules.target.entity.ObservationPoint;
import com.eduction.modules.target.entity.SonTarget;
import com.eduction.resource.BaseController;
import com.eduction.service.*;
import com.eduction.vo.SchoolItemDataVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/check")
public class CheckController extends BaseController {

    static final Log logger = LogFactory.getLog(CheckController.class);

    @Value("${file_path}")
    private String filePath;

    @Autowired
    private SchoolItemDataService schoolItemDataService;
    @Autowired
    private ArgumentationMaterialService argumentationMaterialService;
    @Autowired
    private SonTargetService sonTargetService;
    @Autowired
    DetailedService detailedService;
    @Autowired
    SchoolService schoolService;
    @Autowired
    ObservationPointService observationPointService;
    @Autowired
    private IndexTargetEntityService indexTargetEntityService;

    /**
     * 数据填报查看
     * 根据学校ID，细节id查询学校上传文件
     *
     * @param request
     * @param schoolId
     * @param itemId
     * @return
     */
    @RequestMapping(value = "/underSchoolFile", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> queryAllIndexTarget(HttpServletRequest request, @RequestParam(value = "school_id", required = true) String schoolId, @RequestParam(value = "item_id", required = true) String itemId) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        List<SchoolItemData> list = null;
        try {
            School school = schoolService.querySchoolById(schoolId);
            String type = "";
            if ("1495071155575000".equals(school.getP_type_id())) {
                type = "0";
            } else {
                type = "1";
            }
            List<SonTarget> sonTargetList = sonTargetService.querySonTargetByFid(itemId);
            for (SonTarget st : sonTargetList) {
                List<Detailed> detailedList = detailedService.queryDetailedByFid(st.getP_id(), type);
                for (Detailed d : detailedList) {
                    List<ObservationPoint> observationPointList = observationPointService.queryObservationPointByFid(d.getP_id());
                    for (ObservationPoint op : observationPointList) {
                        List<SchoolItemData> schoolItemDataList = schoolItemDataService.querySchoolItemDataByItemIdAndSchoolId(op.getP_id(), schoolId,null);
                        List<SchoolItemDataVo> vos = new ArrayList<>();
                        for (SchoolItemData sid : schoolItemDataList) {
                            if (sid.getS_value() != null) {
                                String[] strarr1 = sid.getS_value().split(",");
                                for (String s : strarr1) {
                                    SchoolItemDataVo vo = new SchoolItemDataVo();
                                    vo.setP_id(sid.getP_id());
                                    vo.setS_school_id(sid.getS_school_id());
                                    if (s != null && !"".equals(s)) {
                                        vo.setPath(s);
                                        String[] strarr2 = s.split("/");
                                        if (strarr2.length != 0)
                                            System.out.println(s);
                                        vo.setS_value(strarr2[4]);
                                        vos.add(vo);
                                    }
                                }
                            }

                        }
                        op.setSchoolItemDataVoList(vos);
                    }
                    d.setList(observationPointList);
                }
                st.setList(detailedList);
            }
//            list = schoolItemDataService.querySchoolItemDataBySchoolId(itemId, schoolId);
            return toResponse(sonTargetList, ReturnCode.SUCCESS, "查询成功!");
        } catch (SQLException e) {
            logger.error(e);
            return toResponse(null, ReturnCode.SUCCESS, "查询异常!");
        }

    }


    /**
     * 管理员
     * 根据学校ID查询学校上传文件
     *
     * @param request
     * @param schoolId
     * @return
     */
    @RequestMapping(value = "/underSchoolFileAll", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> underSchoolFileAll(HttpServletRequest request, @RequestParam(value = "school_id", required = true) String schoolId,@RequestParam(value = "year", required = true) String year) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        List<SchoolItemData> list = null;
        try {
            School school = schoolService.querySchoolById(schoolId);
            String type = "";
            if ("1495071155575000".equals(school.getP_type_id())) {
                type = "0";
            } else {
                type = "1";
            }

            List<IndexTargetEntity> indexTargetEntityList=indexTargetEntityService.queryAllIndexTarget();
            for(IndexTargetEntity entity:indexTargetEntityList) {
                List<SonTarget> sonTargetList = sonTargetService.querySonTargetByFid(entity.getP_id());
                for (SonTarget st : sonTargetList) {
                    List<Detailed> detailedList = detailedService.queryDetailedByFid(st.getP_id(), type);
//                    for (Detailed d : detailedList) {
//                        List<ObservationPoint> observationPointList = observationPointService.queryObservationPointByFid(d.getP_id());
//                        for (ObservationPoint op : observationPointList) {
//                            List<SchoolItemData> schoolItemDataList = schoolItemDataService.querySchoolItemDataByItemIdAndSchoolId(op.getP_id(), schoolId,year);
//                            List<SchoolItemDataVo> vos = new ArrayList<>();
//                            for (SchoolItemData sid : schoolItemDataList) {
//                                if (sid.getS_value() != null) {
//                                    String[] strarr1 = sid.getS_value().split(",");
//                                    for (String s : strarr1) {
//                                        SchoolItemDataVo vo = new SchoolItemDataVo();
//                                        vo.setP_id(sid.getP_id());
//                                        vo.setS_school_id(sid.getS_school_id());
//                                        if (s != null && !"".equals(s)) {
//                                            vo.setPath(s);
//                                            String[] strarr2 = s.split("/");
//                                            if (strarr2.length != 0)
//                                                System.out.println(s);
//                                            vo.setS_value(strarr2[4]);
//                                            vos.add(vo);
//                                        }
//                                    }
//                                }
//
//                            }
//                            op.setSchoolItemDataVoList(vos);
//                        }
//                        d.setList(observationPointList);
//                    }
                    st.setList(detailedList);
                }
                entity.setList(sonTargetList);
            }

            return toResponse(indexTargetEntityList, ReturnCode.SUCCESS, "查询成功!");
        } catch (SQLException e) {
            logger.error(e);
            return toResponse(null, ReturnCode.SUCCESS, "查询异常!");
        }

    }

    /**
     * 数据填报查看
     * 根据路径预览文件
     *
     * @param request
     * @param response
     * @param path
     * @return
     */
    @RequestMapping(value = "/getData", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void getData(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String path) {
//        SchoolItemData data = schoolItemDataService.queryById(p_id);
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return ;
        }
        String pathNeed = filePath + path;
        File srcFile = new File(pathNeed);

        String filename = srcFile.getName();
        String name = null;
        try {
            name = filename.substring(0, filename.indexOf(".")) + ".pdf";
        } catch (Exception e) {
            String[] s = path.split("/");
            path = s[0] + "/" + s[1] + "/" + s[2] + "/" + s[3];
            srcFile = new File(filePath + path);
            String test[];
            test = srcFile.list();
            for (String aTest : test) {
                System.out.println(aTest);
                name = filePath + path + "/" + aTest;
            }
            srcFile = new File(name);
        }
        response.setHeader("Content-Type", "text/plain");
        try {
            response.addHeader("Content-Disposition", "inline;filename=" + new String(name.getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            return toResponse(null, ReturnCode.FAIL, "获取文件异常!");
        }
//        response.addHeader("Content-Length", "" + srcFile.length());
        File file = new File(pathNeed + ".pdf");
        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        FileInputStream fileInputStream = null;
        try {
//            if(!file.exists()){
//                file.createNewFile();
//            }
            inputStream = new FileInputStream(srcFile);
            out = response.getOutputStream();
            if (filename.endsWith(".docx")) {
                DocxToPDFConverter converter = new DocxToPDFConverter(inputStream, out, true, true);
                converter.convert();
                fileInputStream = new FileInputStream(file);
            } else if (filename.endsWith(".doc")) {
                DocToPDFConverter converter = new DocToPDFConverter(inputStream, out, true, true);
                converter.convert();
                fileInputStream = new FileInputStream(file);
            }
            byte[] buffer = new byte[1024];
				        /* while (b != -1){
				            b = inputStream.read(buffer);
				            //4.写到输出流(out)中
				            out.write(buffer,0,b);
				         } */
            int count = 0;
            if (fileInputStream == null) {
                fileInputStream = inputStream;
            }
            while ((count = fileInputStream.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        } catch (Exception e) {
            logger.info("获取文件异常", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (out != null) {
                    out.close();
                    out.flush();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


//        //2 创建文件字节输入流对象，并接在源上
//        InputStream in = null;
//        try {
//            in = new FileInputStream(srcFile);
//            byte b[]=new byte[(int)srcFile.length()];//创建合适文件大小的数组
//            in.read(b);    //读取文件中的内容到b[]数组
//            in.close();
//            System.out.println(new String(b));
//            return toResponse(b, ReturnCode.SUCCESS, "获取文件成功!");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;

    /**
     * 根据学校查询答辩论证材料
     *
     * @param request
     * @param schoolId
     * @return
     */
    @RequestMapping(value = "/queryArgumentationMaterial", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> saveArgumentationMaterial(HttpServletRequest request, @RequestParam(value = "schoolId", required = true) String schoolId) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        ArgumentationMaterial aM = null;
        try {
            aM = argumentationMaterialService.findBySchoolId(schoolId);
            if (aM != null) {
                return toResponse(aM, ReturnCode.SUCCESS, "查询答辩论证材料成功!");
            } else {
                return toResponse(null, ReturnCode.FAIL, "查询答辩论证材料失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponse(null, ReturnCode.FAIL, "查询答辩论证材料失败!");
        }
    }

    /**
     * 添加或修改答辩论证材料
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/saveArgumentationMaterial", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> saveArgumentationMaterial(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        String schoolId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
//        String schoolId="111";
        String filePath = map.get("file_path");
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
        try {
            ArgumentationMaterial aM = argumentationMaterialService.findBySchoolId(schoolId);
            if (aM != null) {
                aM.setSchoolId(schoolId);
                aM.setCreateTime(new Date());
                aM.setFilePath(filePath);
                aM.setFileName(fileName);
                argumentationMaterialService.save(aM);
            } else {
                ArgumentationMaterial argumentationMaterial = new ArgumentationMaterial();
                argumentationMaterial.setSchoolId(schoolId);
                argumentationMaterial.setCreateTime(new Date());
                argumentationMaterial.setFilePath(filePath);
                argumentationMaterial.setFileName(fileName);
                argumentationMaterialService.save(argumentationMaterial);
            }
            return toResponse(null, ReturnCode.SUCCESS, "保存答辩论证材料成功!");
        } catch (Exception e) {
            return toResponse(null, ReturnCode.FAIL, "保存答辩论证材料失败!");
        }
    }

    /**
     * 下载文件
     *
     * @param request
     * @param response
     * @param path
     */
    @RequestMapping(value = "/download", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String path) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return ;
        }
        String pathNeed = filePath + path;
        File srcFile = new File(pathNeed);

        String filename = srcFile.getName();
        String name = null;

        try {
            name = filename.substring(0, filename.indexOf(".")) + ".pdf";
        } catch (Exception e) {
            String[] s = path.split("/");
            path = s[0] + "/" + s[1] + "/" + s[2] + "/" + s[3];
            srcFile = new File(filePath + path);
            String test[];
            test = srcFile.list();
            for (String aTest : test) {
                System.out.println(aTest);
                name = pathNeed + "/" + aTest;
            }
            srcFile = new File(name);
        }


        response.setHeader("Content-Type", "text/plain");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            return toResponse(null, ReturnCode.FAIL, "获取文件异常!");
        }
        response.addHeader("Content-Length", "" + srcFile.length());


        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(srcFile);
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
				        /* while (b != -1){
				            b = inputStream.read(buffer);
				            //4.写到输出流(out)中
				            out.write(buffer,0,b);
				         } */
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        } catch (Exception e) {
            logger.info("获取文件异常", e);
        } finally {
            try {
                inputStream.close();
                out.close();
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 下载文件excel
     *
     * @param request
     * @param response
     * @param path
     */
    @RequestMapping(value = "/downloadExcel", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "path", required = true) String path) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return;
        }
        String pathNeed = filePath + path;
        File srcFile = new File(pathNeed);

        String filename = srcFile.getName();
//        String name = null;

//        try {
//            name = filename.substring(0, filename.indexOf(".")) + ".pdf";
//        } catch (Exception e) {
//            String[] s = path.split("/");
//            path = s[0] + "/" + s[1] + "/" + s[2] + "/" + s[3];
//            srcFile = new File(filePath + path);
//            String test[];
//            test = srcFile.list();
//            for (String aTest : test) {
//                System.out.println(aTest);
//                name = pathNeed + "/" + aTest;
//            }
//            srcFile = new File(name);
//        }


        response.setHeader("Content-Type", "text/plain");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            return toResponse(null, ReturnCode.FAIL, "获取文件异常!");
        }
        response.addHeader("Content-Length", "" + srcFile.length());


        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(srcFile);
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
				        /* while (b != -1){
				            b = inputStream.read(buffer);
				            //4.写到输出流(out)中
				            out.write(buffer,0,b);
				         } */
            int count = 0;
            while ((count = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
        } catch (Exception e) {
            logger.info("获取文件异常", e);
        } finally {
            try {
                inputStream.close();
                out.close();
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 添加二维码
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/tbCodeUrl", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> tbCodeUrl(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        String schoolId = map.get("school_id");
        if (null == schoolId) {
            return toResponse(null, ReturnCode.FAIL, "学校id不能为空");
        }
        String filePath = map.get("file_path");
        try {

            QuestionnaireSurvey qs = new QuestionnaireSurvey();
            qs.setSchool_id(schoolId);
            qs.setTb_code_url(filePath);
            schoolService.saveQuestionnaireSurvey(qs);
            return toResponse(null, ReturnCode.SUCCESS, "保存二维码成功!");
        } catch (Exception e) {
            return toResponse(null, ReturnCode.FAIL, "保存二维码失败!");
        }
    }

    /**
     * 添加二维码结果
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/tbCodeResultUrl", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> tbCodeResultUrl(HttpServletRequest request, @RequestBody Map<String, String> map) {
        String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(StringUtils.isEmpty(user_type)){
            return toResponse(null,ReturnCode.FAIL,"暂无权限！");
        }
        String schoolId = map.get("school_id");
        if (null == schoolId) {
            return toResponse(null, ReturnCode.FAIL, "学校id不能为空");
        }
        String filePath = map.get("file_path");
        try {

            QuestionnaireSurvey qs = new QuestionnaireSurvey();
            qs.setSchool_id(schoolId);
            qs.setTb_code_result_url(filePath);
            schoolService.saveQuestionnaireSurvey(qs);
            return toResponse(null, ReturnCode.SUCCESS, "保存二维码成功!");
        } catch (Exception e) {
            return toResponse(null, ReturnCode.FAIL, "保存二维码失败!");
        }
    }

    /**
     * 获取二维码/结果
     * @param request
     * @param schoolId
     * @return
     */
    @RequestMapping(value = "/getTbCodeUrl", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getTbCodeUrl(HttpServletRequest request, @RequestParam(value = "schoolId", required = true) String schoolId) {
        try {
            String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
            if(StringUtils.isEmpty(user_type)){
                return toResponse(null,ReturnCode.FAIL,"暂无权限！");
            }
            QuestionnaireSurvey qs = schoolService.getTbCodeUrl(schoolId);
            return toResponse(qs, ReturnCode.SUCCESS, "获取二维码成功!");
        } catch (Exception e) {
            return toResponse(null, ReturnCode.FAIL, "获取二维码失败!");
        }
    }

    public static  void  main(String args[]) {
        String result = Integer.toBinaryString(-108);
        System.out.println(result);
    }
}
